const bcrypt = require('bcrypt')
const {User,userValidator} = require('../model/user')
const {sendCode,randomCode,fetchAddress} = require('../utils')
const validator = require('../middleware/validator')
const {SMSCode,smsCodeValidator} = require('../model/smscode')
const moment = require('moment-timezone')
const jwt = require('jsonwebtoken')
const config = require('../config')
exports.login = async (req, res, next) => {
    try {
        const validValue = req.validValue
        let user = await User.findOne({
            phone: validValue.phone
        }).select("+phone +password +status")
        const province = [
            "北京", "天津", "河北", "辽宁", "吉林", "黑龙江", "山东", "江苏", "上海", "浙江", "安徽", "福建", "江西",
            "广东", "广西", "海南", "河南", "湖南", "湖北", "山西", "内蒙古", "宁夏", "青海", "陕西", "甘肃", "新疆",
            "四川", "贵州", "云南", "重庆", "西藏", "香港", "澳门", "台湾"
        ]
        let perLocation = ''
        let headerip = req.headers['x-forwarded-for'] ||
            req.ip ||
            req.connection.remoteAddress ||
            req.socket.remoteAddress ||
            req.connection.socket.remoteAddress || '';

        if (headerip.split(',').length > 0) {
            headerip = headerip.split(',')[0]
        }
        headerip = headerip.substr(headerip.lastIndexOf(':') + 1, headerip.length);
        let ips = await fetchAddress(headerip)

        let ip = ips.data
        if (!ip) {
            perLocation = '未知IP'
        } else {
            //去除换行
            ip = ip.replace(/[\r\n]/g, "")
            for (let i in province) {
                let regtest = new RegExp(province[i])
                if (ip.match(regtest)) {
                    perLocation = province[i];
                    break
                } else {
                    perLocation = "未知IP"
                }
            }
        }
        if (!user) {
            return res.status(200).json({
                code: 400,
                msg: '登录失败，该用户名可能未注册'
            })
        }
        if (user.status!=1){
            return res.status(200).json({
                code: 400,
                msg: '登录失败，该账号已被冻结'
            })
        }
        //解密并对比
        let isRight = await bcrypt.compare(validValue.password, user.password)
        if (!isRight) {
            return res.status(200).json({
                code: 400,
                msg: '用户名或密码错误'
            })
        }
        let userinfo = await User.findOne({
            _id: user._id
        }).populate('avatar')
        await User.findByIdAndUpdate(user._id, {
            perLocation: perLocation
        })
        res.status(200).json({
            code: 200,
            msg: '登录成功',
            data: {
                token: user.generateToken(),
                userInfo: userinfo
            }
        })
    } catch (err) {
        next(err)
    }
}

exports.sendCode = async (req, res, next) => {
    try {
        let phone = req.query.phone
        let sendPhone = await SMSCode.find({phone:phone})
        
        if (sendPhone.length>=1){
            return res.status(200).json({
                code:400,
                msg:"您发送短信的频率过快，请稍后再发"
            })
        }

        var code = randomCode(6);
        let result = await sendCode(phone, code)

        if (!result) {
            return res.status(200).json({
                code: 400,
                msg: "获取验证码失败1"
            })
        }
        const smscodes = new SMSCode({
            ...result,
            createdAt: moment().tz("Asia/Shanghai").format('YYYY/MM/DD HH:mm:ss')
        })
        await smscodes.save()
        res.status(200).json({
            code: 200,
            msg: "获取验证码成功"
        })
        setTimeout(async () => {
            await SMSCode.findByIdAndRemove(smscodes._id)
        }, 90000);
    } catch (err) {
        next(err)
    }
}

exports.loginByCode = async (req, res, next) => {
    try {
        const {
            phone,
            code
        } = req.body
        let result = await SMSCode.find({
            phone:phone,
            code:code
        })
        console.log(result)
        if (result.length == 0) {
            return res.status(200).json({
                code: 400,
                msg: "登录失败，验证码错误"
            })
        }
        let user = await User.findOne({
            phone: phone
        }).select("+phone")
        let randomStr = Math.random().toString(36).slice(-8)
        if (!user || user.length == 0) {
            user = new User({
                phone: phone,
                nickname: '新用户' + randomStr,
                createdAt: moment().tz("Asia/Shanghai").format('YYYY/MM/DD HH:mm:ss')
            })
        }
        if (!user) {
            return res.status(200).json({
                code: 400,
                msg: "登录失败"
            })
        }
        let userinfo = await User.findOne({
            _id: user._id
        }).populate('avatar')
        const province = [
            "北京", "天津", "河北", "辽宁", "吉林", "黑龙江", "山东", "江苏", "上海", "浙江", "安徽", "福建", "江西",
            "广东", "广西", "海南", "河南", "湖南", "湖北", "山西", "内蒙古", "宁夏", "青海", "陕西", "甘肃", "新疆",
            "四川", "贵州", "云南", "重庆", "西藏", "香港", "澳门", "台湾"
        ]
        let perLocation = ''
        let headerip = req.headers['x-forwarded-for'] ||
            req.ip ||
            req.connection.remoteAddress ||
            req.socket.remoteAddress ||
            req.connection.socket.remoteAddress || '';

        if (headerip.split(',').length > 0) {
            headerip = headerip.split(',')[0]
        }
        headerip = headerip.substr(headerip.lastIndexOf(':') + 1, headerip.length);
        let ips = await fetchAddress(headerip)

        let ip = ips.data
        if (!ip) {
            perLocation = '未知IP'
        } else {
            //去除换行
            ip = ip.replace(/[\r\n]/g, "")
            for (let i in province) {
                let regtest = new RegExp(province[i])
                if (ip.match(regtest)) {
                    perLocation = province[i];
                    break
                } else {
                    perLocation = "未知IP"
                }
            }
        }
        await User.findByIdAndUpdate(user._id, {
            perLocation: perLocation
        })
        let token = jwt.sign({
            _id: user._id
        }, config.secret, {
            expiresIn: '7day'
        })
        res.status(200).json({
            code: 200,
            msg: "登录成功",
            data: {
                token: token,
                userInfo: userinfo
            }
        })
    } catch (err) {
        next(err)
    }
}